package com.example.ruiji.common;

import com.example.ruiji.pojo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

//全局异常处理
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex)
    {
log.error(ex.getMessage());
//截取字符匹配错误
        if(ex.getMessage().contains("Duplicate entry"))
        {
            String[] split=ex.getMessage().split(" ");
            String mg=split[2]+"已重复";
            return R.error(mg);
        }


        return R.error("未知错误 请联系管理员"+ex.getMessage());
    }
//捕获我们自写的异常
    @ExceptionHandler({CustomException.class})
    public R<String> exceptionHandler(CustomException ex)
    {

        return R.error(ex.getMessage());
    }

}
